const install = (Vue, vm) => {

	/**
	 * 是否登录
	 */
	const isLogin = () => {
		// 如果没有token 跳转到登录页面
		const token = vm.vuex_token;
		if (!token) {
			const currentPage = getCurrentPages().pop();

			// // 获取页面路径和请求参数
			// const {options, route} = currentPage;
			// // 参数的key
			// const optionsKeys = Object.keys(options);
			// let params = '';
			// if (optionsKeys.length !== 0) {
			// 	params = optionsKeys.reduce((pre, current) => {
			// 		return `${pre}${current}=${options[current]}&`
			// 	}, '?').slice(0, -1);
			// }

			var pages = getCurrentPages() // 获取栈实例
			let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由

			// 如果当前是失败页 什么都不处理 缓存请求成功直接返回false (失败页跳转逻辑在 fail.vue 中独立实现)
			if (currentRoute === 'pages/index/fail') {
				return false;
			}

			// 如果当前不是登录页 就跳转
			if (currentRoute !== 'pages/auth/login') {
				// 缓存当前页 用于登录或者注册之后的跳转
				uni.setStorageSync('back_url', currentPage.route);
				
				vm.$u.toast('请登录');
				setTimeout(() => {
					vm.$u.route({
						type: 'redirect',
						url: '/pages/auth/login'
					})
				}, 500)
			}
			return false;
		}
		return true;
	}

	/**
	 * 跳转请求失败页
	 */
	const goToFailPage = () => {
		setTimeout(() => {}, 500) // 缓冲时间0.5s 防止重复跳转到失败页
		
		var pages = getCurrentPages() // 获取栈实例
		let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由

		// 如果当前不是失败页 就跳转
		if (currentRoute !== 'pages/index/fail') {
			setTimeout(() => {
				vm.$u.route({
					type: 'reLaunch',
					url: '/pages/index/fail'
				})
			}, 500)
		}
	}

	/**
	 * 开启通知权限
	 */
	const permissions = () => {
		// #ifdef APP-PLUS
		var main = plus.android.runtimeMainActivity();
		var pkName = main.getPackageName();
		var uid = main.getApplicationInfo().plusGetAttribute("uid");
		var NotificationManagerCompat = plus.android.importClass(
			"android.support.v4.app.NotificationManagerCompat");
		//android.support.v4升级为androidx
		if (NotificationManagerCompat == null) {
			NotificationManagerCompat = plus.android.importClass("androidx.core.app.NotificationManagerCompat");
		}
		var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
		// 未开通‘允许通知’权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置  
		if (!areNotificationsEnabled) {
			uni.showModal({
				title: '通知权限开启提醒',
				content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
				showCancel: false,
				confirmText: '去设置',
				success: function(res) {
					if (res.confirm) {
						var Intent = plus.android.importClass('android.content.Intent');
						var Build = plus.android.importClass("android.os.Build");
						//android 8.0引导  
						if (Build.VERSION.SDK_INT >= 26) {
							var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
							intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
						} else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0  
							var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
							intent.putExtra("app_package", pkName);
							intent.putExtra("app_uid", uid);
						} else { //(<21)其他--跳转到该应用管理的详情页  
							intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
							var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
							intent.setData(uri);
						}
						// 跳转到该应用的系统通知设置页  
						main.startActivity(intent);
					}
				}
			});
		}
		// #endif
	}

	/**
	 * 消息推送
	 */
	const appPushInfo = (cids, title, content, data) => {
		// #ifdef APP-PLUS
		return new Promise((resolve) => {
			const request_id = getId();
			uniCloud.callFunction({
				name: 'pushMessage',
				data: {
					cids,
					title,
					content,
					data,
					request_id
				}
			}).then((res) => {
				resolve(res.success)
			}).catch(() => {
				resolve(false);
			})
		});
		// #endif
	}

	/**
	 * px转rpx
	 * @param {Object} px
	 */
	const pxTorpx = (px) => {
		let deviceWidth = wx.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
		let rpx = (750 / deviceWidth) * Number(px)
		return Math.floor(rpx);
	}

	/**
	 * rpx转px
	 * @param {Object} rpx
	 */
	const rpxTopx = (rpx) => {
		let deviceWidth = wx.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
		let px = (deviceWidth / 750) * Number(rpx)
		return Math.floor(px);
	}

	function getId() {
		let yy = new Date().getFullYear();
		let mm = new Date().getMonth() + 1;
		let dd = new Date().getDate();
		let hh = new Date().getHours();
		let mf =
			new Date().getMinutes() < 10 ?
			"0" + new Date().getMinutes() :
			new Date().getMinutes();
		let ss =
			new Date().getSeconds() < 10 ?
			"0" + new Date().getSeconds() :
			new Date().getSeconds();
		let Randnum = "";
		for (var i = 0; i < 10; i++) {
			Randnum += Math.floor(Math.random() * 10);
		}
		return "ID_" + yy + mm + dd + hh + mf + ss + Randnum;
	}

	vm.$u.utils = {
		isLogin,
		permissions,
		appPushInfo,
		pxTorpx,
		rpxTopx,
		goToFailPage
	}

}

export default {
	install
}